package org.dormi.learn;

import java.io.File;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * 演示冲突
 * 01_main的pom.xml中 添加了 jackson-core-2.5.4
 * 02_res的pom.xml中 添加了 jackson-core-2.11.0
 * <p>
 * 本想试用 URLClassLoader jackson-core-2.11.0, 但实际会不成功
 * <p>
 * 那么进行class load时, 如果 CustomClassLoader的 parent=AppClassLoader
 * 那么实际加载的时 v2.5.4的 jackson-core (双亲委派 AppClassLoader能够加载到 01_main模块中的class)
 *
 * @author : dormi330
 * @since : 22/04/21
 */
public class CustomClassLoader02 {
    public static void main(String[] args) throws Exception {
        File file1 = new File("E:\\workspace\\java_basic\\class_loader\\02_res\\target\\abc.jar");
        // 想加载的是 v2.11.0
        File file2 = new File("E:\\workspace\\java_basic\\class_loader\\doc\\jackson-core-2.11.0.jar");
        URL[] urls = new URL[]{file1.toURI().toURL(), file2.toURI().toURL()};
        // 但是 loader1加载相关类时, 委托 parent加载
        // parent加载时, 加载了 v2.5.4, 就不在加载 v2.11.0了
        URLClassLoader loader1 = new URLClassLoader(urls);


        // 要确保本module 内没有 foo.bar.Demo01
        Class<?> clazz = loader1.loadClass("foo.bar.Demo01");
        System.out.println(clazz.getClassLoader());
        Object obj = clazz.newInstance();
        Method method = clazz.getMethod("parse");
        method.invoke(obj);
    }
}
/*
java.net.URLClassLoader@2503dbd3
before parse
Exception in thread "main" java.lang.reflect.InvocationTargetException
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.dormi.learn.CustomClassLoader02.main(CustomClassLoader02.java:36)
Caused by: java.lang.NoSuchMethodError: com.fasterxml.jackson.core.JsonFactory.getFormatGeneratorFeatures()I
	at foo.bar.Demo01.parse(Demo01.java:18)
	... 5 more
*/
